<template>
  <div ref="barChart" style="width: 100%; height: 300px"></div>
</template>
  
  <script>
import * as echarts from "echarts";

export default {
  name: "BarChart",
  props: ["chartData"],
  watch: {
    chartData: {
      deep: true,
      handler(newData) {
        this.$nextTick(() => {
          this.renderChart(newData);
        });
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.renderChart(this.chartData);
    });
  },
  methods: {
    renderChart(data) {
      const chartDom = this.$refs.barChart;
      const myChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.xArr,
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: data.yArr,
            type: "bar",
            label: {
              show: true, // 显示标签
              position: "top", // 标签位置为柱子顶部
              valueAnimation: true,
              formatter: "{c}", // 显示数值
              color: "#000", // 可根据背景色调整字体颜色
            },
          },
        ],
      };

      myChart.setOption(option, true);
    },
  },
};
</script>